
const md5 = require('md5')
const User = require("../models/User");
const validate = require('validate.js');
const { pick } = require('../utils/propertyHelper');


// 增加
exports.addUser = async function(userObj){
    userObj = pick(userObj,'name','loginId','loginPwd');
     // 验证规则
     const rule = {
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string",
            length: {
                minimum: 1,
                maximum: 15
            }

        },
        loginId:{
            presence: {
                allowEmpty: false,
            },
            email:true
        },
        loginPwd: {
            presence: {
                allowEmpty: false,
            },
            type: "string",
            length: {
                minimum: 6,
                maximum: 20
            }
        }
    }
    // 涉及数据库数据查询 异步验证
    try {
        await validate.async(userObj, rule);
    } catch (err) {
        console.log(err);
    }

    userObj.loginPwd = md5(userObj.loginPwd);
    const ins = await User.create(userObj);
    return ins.toJSON();
};
// 删除
exports.deleteUser = async function(userId){
    const result = await User.destroy({
        where:{
            id: userId
        }
    });
    return result;
};
//改
exports.updateUser = async function(id,UserObj){
    if(userObj.loginPwd){
        userObj.loginPwd = md5(userObj.loginPwd);
    }
    const result = await User.update(userObj,{
        where:{
            id,
        },
    });
    return result;
};

exports.login = async function(loginId,loginPwd){
    // 一样的密码通过md5加密后字符串一样
    loginPwd = md5(loginPwd);
    // 查询单个数据
    const result = await User.findOne({
        where:{
            loginId,
            loginPwd
        }
    });
    // 大小写区分
    if(result && result.loginId === loginId){
        return result.toJSON();
    }
    return null;
}
// 根据主键来查询
exports.getUserById = async function(id){
    const result = await User.findByPk(id);
    if(result){
        return result.toJSON();
    }
    return null;
}

// 查询有多少用户
exports.getAllUser = async function(){
    const result = await User.count();
    return result;
}

// 
